package org.xdq.原子操作;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test2 {

    static int[] arr = new int[10];

    static class Listener extends Thread{

        private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

        private List<Integer> list = new ArrayList<>();
        private int max_count;
        private int count;

        public Listener(int max_count){
            this.max_count = max_count;
        }

        public void add(Integer n,int idx){
            readWriteLock.writeLock().lock();
            try {
                if(idx<list.size()){
                    list.set(idx, n);
                }else{
                    list.add(n);
                }
                count++;
                if(this.isFull()){
                    synchronized (this){
                        this.notify();
                    }
                }
            } finally {
                readWriteLock.writeLock().unlock();
            }
        }

        public boolean isFull(){
            readWriteLock.readLock().lock();
            try {
                return count==max_count;
            } finally {
                readWriteLock.readLock().unlock();
            }
        }

        public String getData(){
            readWriteLock.readLock().lock();
            try {
                return Arrays.toString(list.toArray());
            } finally {
                readWriteLock.readLock().unlock();
            }
        }

        @Override
        public void run() {
            synchronized (this){
                while(!this.isFull()){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            System.out.println(getData());
        }
    }

    public static void main(String[] args) {

        Listener listener = new Listener(100);
        listener.start();

        List<Thread> list = new ArrayList<>();

        for(int i=0;i<10;i++){
            list.add(new Thread(){

                public void run() {

                   for(int j=0;j<arr.length;j++){


                           for(int i=0;i<1000;i++){

                               synchronized (listener) {
                                   arr[j]++;
                               }

                           }


                       listener.add(arr[j],j);

                   }
                }
            });
        }

        list.forEach(t->{t.start();});



    }

}
